package gw.com.android.recovery;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import gw.com.android.utils.AppJsonUtil;
import gw.com.android.utils.ZipUtils;
import java.io.File;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import www.com.library.app.Logger;
import www.com.library.util.JsonUtil;

/**
 * Created by spence on 17-8-24.
 * more about @see <a href="http://192.168.35.161:9009/apidoc/baseservice/#api-API_upload_file-uploadWithFile">api documentation</a>
 * and @see <a href="http://192.168.35.81/apidoc/config-center/#api-APP-accountConfig">api documentation</a>
 */

public class RecoveryManager {


  private String UPLOAD_URL;
  private String CHECK_URL;
  private String LOG_FILE_PATH;
  private String ZIP_LOG_FILE_PATH;
  /** httpclient moudle **/
  private OkHttpClient mOkHttpClient;
  private String channel="app";
  /** fx:外汇，hx：恒信，pm：贵金属，cf：创富 **/
  private String COMPANY_ID_TAG;
  private String COMPANY_ID;
  /** 上传接口验证key **/
  private String encryptKey;

  /** 需要上传 **/
  private static final String NEED_RECOVER="1";
  /** 无需上传 **/
  private static final String NOT_RECOVER="0";

  public RecoveryManager(String uploadurl,String checkurl,String logFilePath,String zipLogFilePath,String companyIdTag,String encryptKey,String companyId){
    UPLOAD_URL=uploadurl;
    CHECK_URL=checkurl;
    LOG_FILE_PATH=logFilePath;
    ZIP_LOG_FILE_PATH=zipLogFilePath;
    COMPANY_ID_TAG=companyIdTag;
    mOkHttpClient=new OkHttpClient.Builder().build();
    this.encryptKey=encryptKey;
    COMPANY_ID=companyId;
  }

  /**
   * 检查是否上传
   * @param accountNo 账户
   * @return
   */
  public void checkNeedRecover(final String accountNo){


    RequestBody requestBody=new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("companyId",COMPANY_ID)
        .addFormDataPart("accountNo",accountNo)
        .addFormDataPart("type","upload_log")
        .build();

    final Request request =new  Request.Builder().url(CHECK_URL).post(requestBody).build();
    mOkHttpClient.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
        System.out.println("");
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try {
          String json=response.body().string();
          Logger.e("RecoveryManager checkNeedRecover = " + json);
          if(JsonUtil.isJsonData(json)){
            Gson gson=new GsonBuilder().create();
            ResponseConfig responseConfig=gson.fromJson(json,ResponseConfig.class);
            if (responseConfig.getData().getStatus().equals(NEED_RECOVER)){
              createLogZip();
              updataLogFile(accountNo);
            }else if(responseConfig.getData().getStatus().equals(NOT_RECOVER)) {

            }
          }
        }catch (Exception e){
          e.printStackTrace();
        }
      }
    });
  }

  /**
   * 上传文件
   * @param accountNo 账号(可以为账号、手机号)
   * @return
   */
  private void updataLogFile(String accountNo){
    File file=getLogZipFile(ZIP_LOG_FILE_PATH);
    RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
    RequestBody multipartBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("channel",channel)
        .addFormDataPart("accountNo",accountNo)
        .addFormDataPart("companyId",COMPANY_ID_TAG)
        .addFormDataPart("encryptKey",encryptKey)
        .addFormDataPart("file", file.getName(), fileBody)
        .build();

    final Request request = new Request.Builder().url(UPLOAD_URL).post(multipartBody).build();
    mOkHttpClient.newCall(request).enqueue(new Callback() {
      @Override public void onFailure(Call call, IOException e) {
//        delectFileForZip();
      }

      @Override public void onResponse(Call call, Response response) throws IOException {
        try {
          String json=response.body().string();
          Logger.e("RecoveryManager updataLogFile = " + json);
          GsonBuilder builder=new GsonBuilder();
          Gson gson=builder.create();
          ResponseUpFile responseUpFile=gson.fromJson(json,ResponseUpFile.class);
          if (responseUpFile.getMsg().equals("请求成功")){
            delectFileForZip();
          }else {
//            delectFileForZip();
          }
        }catch (Exception e){
          e.printStackTrace();
        }
      }
    });


  }


  /**
   * 获取压缩文件zip
   * @return
   */
  private File getLogZipFile(String zipFilePath){
    return new File(zipFilePath);
  }

  /**
   * 创建压缩文件
   * @return
   */
  private boolean createLogZip(){
    return ZipUtils.zipFolder(LOG_FILE_PATH,ZIP_LOG_FILE_PATH);
  }

  /**
   * 删除文件目录下所有的文件
   */
  private void delectFileForPath(){

  }

  /**
   * 删除压缩文件
   */
  private void delectFileForZip(){
    File file=new File(ZIP_LOG_FILE_PATH);
    if(file.exists()&&file.isFile()) {
      file.delete();
    }
  }

}
